#!/bin/bash

# set -x

help() {
    echo "usage: add_wifi.sh <ssid> <psk>"
    exit 1
}

ssid=$1
psk=$2

if [[ "-h" == "$1" ]] || [[ "--help" == "$1" ]]; then
    help
fi

if [[ x"" == x"$ssid" ]]; then
    help
fi

if [[ x"" == x"$psk" ]]; then
    help
fi

FILE_PATH=/etc/wpa_supplicant/wpa_supplicant.conf

content=`grep "ssid=\"${ssid}\"" ${FILE_PATH}`
content=`echo ${content}`
echo content=$content

if [[ x"" == x"$content" ]]; then
    echo "
network={
    ssid=\"$ssid\"
    psk=\"$psk\"
}

    " >> $FILE_PATH
    ret=$?
    if [[ 0 -ne $ret ]]; then
        echo "append to file failed."
        exit $ret
    fi
    # echo "network={" >> $FILE_PATH
    # echo "    ssid=\"$ssid\"" >> $FILE_PATH
    # echo "    psk=\"$psk\"" >> $FILE_PATH
    # echo "}" >> $FILE_PATH

    echo "add success. file:$FILE_PATH"
fi
